package shuaige.jdk.多线程.concurrent.completableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class 处理错误1 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        处理错误1 任意一个完成就返回 = new 处理错误1();
        任意一个完成就返回.完成时抛出异常1();
    }

    public void 有异常时返回默认值() throws ExecutionException, InterruptedException {
        String name = null;
        CompletableFuture<String> completableFuture
                = CompletableFuture.supplyAsync(() -> {
            if (name == null) {
                throw new RuntimeException("Computation error!");
            }
            return "Hello, " + name;
        }).handle((s, throwable) -> {
            System.out.println("s:" + s);
            System.out.println("throwable:" + throwable);
            return "返回默认值";
        });
        System.out.println(completableFuture.get());
    }

    public void 完成时抛出异常() throws ExecutionException, InterruptedException {
        CompletableFuture<String> completableFuture = new CompletableFuture<>();
        // 如果尚未完成，则导致调用get()和相关方法以抛出给定的异常
        completableFuture.completeExceptionally(new RuntimeException("Calculation failed!"));
        completableFuture.get();
    }


    public void 完成时抛出异常1() throws ExecutionException, InterruptedException {
        CompletableFuture<String> f = CompletableFuture.supplyAsync(() -> {
            //测试抛异常后,exceptionally()方法接受并处理
            int x = 1 / 0;
            return "这是一个栗子";
        }).exceptionally(ex -> ex.getCause().getMessage());
        System.out.println("f.join() = " + f.join());
    }
}
